<template>
  <div class="form-management">
    <el-card style="height: 85vh;">
      <vxe-grid ref="gridRef" v-bind="gridOptions" v-on="gridEvents">
        <!-- 操作列插槽 -->
        <template #operate="{ row }">
          <vxe-button
            v-for="btn in inTableButtons"
            :key="btn.code"
            size="small"
            :status="btn.status"
            mode="text"
            :icon="getButtonIcon(btn.code)"
            @click="
              handleRowAction(btn.code, row, {
                openEditPopup: handleEdit,
                removeRow: handleDelete,
              })
            "
            :content="btn.name"
          ></vxe-button>
          <!-- <vxe-button
            status="primary"
            mode="text"
            icon="vxe-icon-edit"
            @click="handleEdit(row)"
            content="编辑"
          ></vxe-button>
          <vxe-button
            status="danger"
            mode="text"
            icon="vxe-icon-delete"
            @click="handleDelete(row)"
            content="删除"
          ></vxe-button> -->
        </template>
      </vxe-grid>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import type {
  VxeGridProps,
  VxeGridInstance,
  VxeGridListeners,
} from "vxe-table";
import { sysDict, queryPage, delEntityById } from "@/api";
import { permToButtons, splitButtonsByLocation } from "@/utils/permission";
import { useTableActions,setupToolbar } from "@/utils/useTableActions";

interface RowVO {
  id?: string | number;
  formName: string;
  className: string;
  tableName: string;
  formType: string;
  isCreateTable: "1" | "0";
  isCreateCode: "1" | "0";
  [key: string]: any;
}

interface PageResult {
  data: RowVO[];
  count: number;
}
const route = useRoute();
const router = useRouter();
const gridRef = ref<VxeGridInstance<RowVO>>();
const vuePermission = ref<any[]>([]);
const inTableButtons = ref<any[]>([]);
// ==================== 字典缓存 ====================
const dictCache = ref<Record<string, { label: string; value: string }[]>>({});

const getDictOptions = async (dictType: string) => {
  if (dictCache.value[dictType]) return dictCache.value[dictType];
  try {
    const res = await sysDict({ field: "type", value: dictType });
    const list = res.childList || [];
    dictCache.value[dictType] = list;
    return list;
  } catch (err) {
    console.error(`加载字典 ${dictType} 失败`, err);
    dictCache.value[dictType] = [];
    return [];
  }
};

const dictLabel = (type: string, value: any) => {
  const map = dictCache.value[type] || [];
  const item = map.find((d) => d.value === String(value));
  return item?.label || "-";
};

// ==================== Grid 配置 + 类型约束 ====================
const gridOptions = reactive<VxeGridProps<RowVO>>({
  border: true,
  showOverflow: true,
  size: "mini",
   printConfig: {},
  importConfig: {},
  exportConfig: {},
  columnConfig: { resizable: true }, 
  sortConfig: { trigger: "cell" },
  toolbarConfig: {
    buttons: [ ],
    refresh: true, 
  },
  formConfig: {
    titleAlign: "right",
    items: [
      {
        field: "formName",
        title: "表单名称",
        itemRender: { name: "VxeInput", props: { placeholder: "请输入" } },
      },
      {
        field: "formType",
        title: "表单类型",
        itemRender: {
          name: "VxeSelect",
          props: { placeholder: "请选择" },
          options: [],
        },
      },
      {
        itemRender: {
          name: "VxeButtonGroup",
          options: [
            { type: "submit", content: "搜索", status: "primary" },
            { type: "reset", content: "重置" },
          ],
        },
      },
    ],
  },
  columns: [
    { type: "checkbox", width: 60 },
    // { type: "seq", title: "序号", width: 60 },
    { field: "formName", title: "表单名称", minWidth: 180, sortable: true },
    { field: "className", title: "实体类名", minWidth: 160 },
    { field: "tableName", title: "表名", minWidth: 180 },
    {
      field: "formType",
      title: "表单类型",
      minWidth: 100,
      formatter: ({ cellValue }) => dictLabel("form_form_type", cellValue),
    },
    {
      field: "isCreateTable",
      title: "生成表",
      minWidth: 90,
      formatter: ({ cellValue }) => (cellValue === "1" ? "是" : "否"),
    },
    {
      field: "isCreateCode",
      title: "生成代码",
      minWidth: 100,
      formatter: ({ cellValue }) => (cellValue === "1" ? "是" : "否"),
    },
    {
      field: "inherit",
      title: "继承类型",
      minWidth: 100,
      formatter: ({ cellValue }) => dictLabel("inherit_type", cellValue),
    },
    {
      title: "操作",
      fixed: "right",
      width: 160,
      slots: { default: "operate" },
    },
  ],
  pagerConfig: {
    pageSize: 20,
    pageSizes: [10, 20, 50, 100],
    layouts: ["Sizes", "PrevPage", "Number", "NextPage", "FullJump", "Total"],
    total: 0,
  },
  data: [],
});

// ==================== 数据相关状态（用于批量操作）====================
const selectedRows = ref<RowVO[]>([]); // 存储选中行

// 重新加载数据（可带查询条件）
const reloadMenuData = async (form: any = {}) => {
  const { currentPage = 1, pageSize = 10 } = gridOptions.pagerConfig;
  await fetchData(currentPage, pageSize, form);
};

// 删除行（示例）
const removeRow = (ids: string) => {
  ElMessageBox.confirm(`确定要删除数据吗？`, "警告", {
    type: "warning",
  })
    .then(async () => {
      const result = await delEntityById("form", { ids: ids });
      if (result.code == 0) {
        ElMessage.success("删除成功");
        await reloadMenuData();
      } else {
        ElMessage.error(result.message);
      }
    })
    .catch(() => {});
};

// ==================== 所有事件统一管理 ✅ ====================
const gridEvents: VxeGridListeners = {
  // 表单提交
  formSubmit({ data }) {
    reloadMenuData(data);
  },
  // 表单重置
  formReset() {
    reloadMenuData();
  },
  // 分页变化
  pageChange({ currentPage, pageSize }) {
    reloadMenuData({ pageNumber: currentPage, pageSize });
  },
  // 工具栏按钮点击
  toolbarButtonClick({ code }) {
    if (code === "add") {
      router.push({ name: "formDetail" });
    } else if (code === "del") {
      if (selectedRows.value.length === 0) {
        ElMessage.warning("请先选择要删除的菜单");
        return;
      }
      const ids = selectedRows.value.map((row) => row.id).join(",");
      removeRow(ids);
    }
  },
  // 用户勾选行变更
  checkboxChange({ $table }) {
    selectedRows.value = $table.getCheckboxRecords();
  },
  checkboxAll({ $table }) {
    selectedRows.value = $table.getCheckboxRecords();
  },
};

// ==================== 其他操作 ====================
const { getButtonIcon, handleRowAction } = useTableActions<RowVO>({
  customAction(row) {
    console.log("自定义操作:", row.name);
  },
});
const handleEdit = (row: RowVO) => {
  router.push({ name: "formDetail", query: { id: row.id } });
};

const handleDelete = (row: RowVO) => {
  removeRow(String(row.id));
};

// ==================== 数据加载 ====================
const fetchData = async (
  pageNum: number,
  pageSize: number,
  form: any
): Promise<void> => {
  try {
    const res = (await queryPage("form", {
      pageNumber: pageNum,
      pageSize,
      ...form,
    })) as unknown as PageResult;

    gridOptions.data = res.data || [];
    gridOptions.pagerConfig.total = res.count || 0;
    const permissions = route.meta.permission || [];
    const allButtons = permToButtons(permissions);
    const { toolbarButtons, inTableButtons: ops } =
      splitButtonsByLocation(allButtons);

    vuePermission.value = toolbarButtons;
    inTableButtons.value = ops; // 存入响应式变量
       gridOptions.toolbarConfig = setupToolbar(vuePermission.value);
  } catch (err) {
    gridOptions.data = [];
    gridOptions.pagerConfig.total = 0;
  }
};

// 初始化字典
// ==================== 初始化表单字典（动态）====================
const initFormDicts = async (
  dictConfigs: { field: string; dictType: string }[]
) => {
  // 并行加载所有字典
  const promises = dictConfigs.map(async ({ field, dictType }) => {
    const options = await getDictOptions(dictType);

    // 找到对应的 form item 并设置 options
    const formItem = gridOptions.formConfig.items?.find(
      (item) => item.field === field
    );
    if (formItem && formItem.itemRender) {
      formItem.itemRender.options = options;
    }
  });

  // 等待全部加载完成
  await Promise.all(promises);

  // 设置默认 formData 防止 undefined
  const defaultFormData: Record<string, any> = {};
  dictConfigs.forEach(({ field }) => {
    defaultFormData[field] = "";
  });
  gridOptions.formConfig.data = Object.assign(
    {},
    gridOptions.formConfig.data,
    defaultFormData
  );

  // 初始加载数据（可选）
  reloadMenuData();
};

onMounted(() => {
  // 动态配置哪些字段需要字典
  initFormDicts([
    { field: "formType", dictType: "form_form_type" },
    { field: "inherit", dictType: "inherit_type" },
  ]);
  reloadMenuData(); // 初始加载
});
</script>
